import { View, Text, Image } from "@tarojs/components";
import Taro, { useLoad,useShareAppMessage } from "@tarojs/taro";
import "./index.scss";
import { useState } from "react";
import { AtIcon } from "taro-ui";
import { request } from "@/utils/request";
import UserDialogLogin from "@/components/UserDialogLogin";
import { isLogin } from "@/utils/tools";
export default function ActivityDetail() {
  const [curActivity, setCurActivity] = useState<any>(null);
  const [qrCodeVisible, setQrCodeVisible] = useState(false);
  const [canTouchMove, setCanTouchMove] = useState(false);
  const [loginDialogVisible, setLoginDialogVisible] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastText, setToastText] = useState("您已参加过该活动");
  let activityId = ''
  let timeHandler = '' as any;
  function judgeJump() {
    if (isLogin()) {
      jumpToDetail();
    } else {
      setLoginDialogVisible(true);
    }
  }
  function jumpToDetail() {
    // 参加活动，获得积分
    request({
      url: "/api/points/activity/gainPointsForActivity/" + curActivity.id,
      method: "post",
      data:{
        activityId: curActivity.id,
        url:''
      },
      success: (data) => {
        console.log("jumpToDetail data:", data);
        // data为true可以领积分，否则不可以
        clearTimeout(timeHandler)
        setShowToast(true)
        timeHandler = setTimeout(() => {
          setShowToast(false)
        },3000)
        if(data){
          setToastText('已赠送' + curActivity.points + '分')
        }else{
          setToastText('您已参加过该活动')
        }
        if (curActivity.actionType === 1) {
          // 跳转到小程序
          Taro.navigateToMiniProgram({
            shortLink: curActivity.actionUrl,
            success: (res) => {
              console.log("跳转成功", res);
            },
          });
        } else {
          //显示二维码
          setQrCodeVisible(true);
        }
      },
    });
  }
  function getActivityDetail(activityId) {
    request({
      url: "/api/points/activity/getPointsActivity/" + activityId,
      method: "get",
      success: (activity) => {
        console.log("getActivityDetail data:", activity);
        activity.detailImageList = activity.detailImage.split(",");
        setCurActivity(activity);
        Taro.setNavigationBarTitle({ title: activity.title });
      },
    });
  }
  function loginSuccessCallback() {
    jumpToDetail();
  }
  useLoad((options: any) => {
    console.log("Page loaded. options：", options);
    activityId = options.activityId;
    if (activityId) {
      getActivityDetail(activityId);
    } else {
      Taro.reLaunch({
        url: "/pages/index/index",
      });
    }
    // let activity = Taro.getStorageSync('/pages/activityDetail/index/activity')

    // console.log('activity:',activity)
    // if(activity){
    //   setCurActivity(activity)
    // }else {
    //   // 没有获取到活动，所以跳转到首页

    // }
  });
  useShareAppMessage((res) => {
    console.log("shareAppMessage curActivity:", curActivity);
    return {
      title: curActivity.title,
      path: `/pages/activityDetail/index?activityId=`+curActivity.id,
      imageUrl: curActivity.coverImage,
      query: "activityId="+curActivity.id,
    }
  })
  return (
    <View className="activityDetail">
      {<View className={['toast',showToast ? 'show':'hide'].join(' ')}>{toastText}</View>}
      {curActivity && (
        <View className="content">
          <View
            className={["detail", canTouchMove ? "canTouchMove" : ""].join(" ")}
          >
            {
              curActivity.detailImageList.map(detailImage=>{
                return <Image
                  className="img"
                  src={detailImage}
                  mode="widthFix"
                ></Image>
              }) 
            }
            
          </View>
          <View
            className="bottom"
            onTouchMove={(event) => {
              event.stopPropagation();
              return false;
            }}
          >
            <Image
              className="img"
              src={curActivity.bottomImage}
              onClick={judgeJump}
              mode="aspectFill"
            ></Image>
          </View>
          {/* 二维码 */}
          <View
            className={["qrcode-layer", qrCodeVisible ? "visible" : ""].join(
              " "
            )}
            onTouchMove={(event) => {
              event.stopPropagation();
              return false
            }}
          >
            <View className="shadow"></View>
            <View
              className="qrcode-content"
            >
              <AtIcon
                className="icon"
                value="close-circle"
                size="16"
                color="#ccc"
                onClick={() => setQrCodeVisible(false)}
              ></AtIcon>
              <Image
                className="img"
                src={curActivity.actionUrl}
                mode="aspectFill"
                show-menu-by-longpress="true"
              ></Image>
              <View className="qrcode-txt">长按二维码报名</View>
            </View>
          </View>
          <UserDialogLogin
            visible={loginDialogVisible}
            title="提示"
            content="请先登录"
            btnText="去登录"
            cancel={() => {
              setLoginDialogVisible(false);
            }}
            close={() => {
              setLoginDialogVisible(false);
            }}
            successCallback={loginSuccessCallback}
          ></UserDialogLogin>
        </View>
      )}
    </View>
  );
}
